package com.light.gulimall.cart.interceptor;

import com.light.common.constants.CartConstants;
import com.light.common.vo.MemberRespVO;
import com.light.gulimall.cart.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoVO> threadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberRespVO loginUser = (MemberRespVO) session.getAttribute("loginUser");

        UserInfoVO userInfoVO = new UserInfoVO();

        //根据loginUser判断是否登录
        if (!ObjectUtils.isEmpty(loginUser)) {
            //已经登录了既要设置userId也要设置userKey
            userInfoVO.setUserId(loginUser.getId());
            getUserKey(request,userInfoVO);
        } else {
            //没有登录，但是cookie中有userkey这个key
            getUserKey(request, userInfoVO);
            //没有登录，cookie中也没有对应的key
            //生成一个，并且存入浏览器的cookie中
            if (StringUtils.isBlank(userInfoVO.getUserKey())) {
                String userKey = UUID.randomUUID().toString();
                userInfoVO.setUserKey(userKey);
                Cookie cookie = new Cookie(CartConstants.TEMP_USER_COOKIE_NAME, userKey);
                cookie.setDomain("gulimall.com");
                cookie.setMaxAge(CartConstants.TEMP_USER_COOKIE_TIMEOUT);
                response.addCookie(cookie);
            }
        }
        threadLocal.set(userInfoVO);
        return true;
    }

    private static void getUserKey(HttpServletRequest request, UserInfoVO userInfoVO) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CartConstants.TEMP_USER_COOKIE_NAME)) {
                    userInfoVO.setUserKey(cookie.getValue());
                }
            }
        }
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
}
